const util = require('../../utils/util');
const DataRoleService = require('../../service/system/data-role.service');

async function listDataRoles(ctx) {
	const { roleName = '', page = 1, limit = 10 } = ctx.query;

	try {
		const result = await DataRoleService.listDataRoles({ roleName, page: +page, limit: +limit });
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询数据角色失败: ${error.message}`);
	}
}

async function getMenuAndDeptLists(ctx) {
	try {
		const result = await DataRoleService.getMenuAndDeptLists();
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `获取菜单和部门列表失败: ${error.message}`);
	}
}

async function getDataRoleById(ctx) {
	const { id } = ctx.params;

	if (!id) {
		return util.fail(ctx, '数据角色 ID 无效');
	}

	try {
		const result = await DataRoleService.getDataRoleById(id);
		if (!result) {
			return util.fail(ctx, '数据角色不存在');
		}
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询数据角色失败: ${error.message}`);
	}
}

async function saveDataRole(ctx) {
	const params = ctx.request.body;
	const { userId } = util.decodeToken(ctx);

	const requiredFields = ['roleName', 'dataScopeCd'];
	for (const field of requiredFields) {
		if (!params[field]) {
			return util.fail(ctx, `缺少必填字段: ${field}`);
		}
	}

	try {
		const result = await DataRoleService.saveDataRole(params, userId);
		util.success(ctx, { id: result });
	} catch (error) {
		util.fail(ctx, `保存数据角色失败: ${error.message}`);
	}
}

async function deleteDataRoles(ctx) {
	const { ids } = ctx.request.body; // 从 body 获取 JSON 数据

	if (!ids || !Array.isArray(ids) || ids.length === 0) {
		return util.fail(ctx, '删除的角色 ID 无效');
	}

	try {
		const result = await DataRoleService.deleteDataRoles(ids);
		if (result.affectedRows === 0) {
			return util.fail(ctx, '没有找到可删除的数据角色');
		}
		util.success(ctx, null);
	} catch (error) {
		util.fail(ctx, `删除数据角色失败: ${error.message}`);
	}
}
async function updateDataRole(ctx) {
	const params = ctx.request.body;
	const { userId } = util.decodeToken(ctx);

	const requiredFields = ['id', 'roleName', 'dataScopeCd'];
	for (const field of requiredFields) {
		if (!params[field]) {
			return util.fail(ctx, `缺少必填字段: ${field}`);
		}
	}

	try {
		const result = await DataRoleService.updateDataRole(params, userId);
		if (!result) {
			return util.fail(ctx, '数据角色不存在或已被删除');
		}
		util.success(ctx, { id: params.id });
	} catch (error) {
		util.fail(ctx, `更新数据角色失败: ${error.message}`);
	}
}
module.exports = { listDataRoles, getMenuAndDeptLists, getDataRoleById, saveDataRole, deleteDataRoles, updateDataRole };
